/*
 * Copyright (c) 2011 Obix Labs Limited
 * Redistribution and use in source and binary forms, 
 * with or without modification, are permitted provided 
 * that the following conditions are met:
 * 
 * 		Redistribution of source code must retain the above 
 * 		copyright notice, this list of conditions and the 
 * 		following disclaimer.
 *
 * 		Redistribution in binary form must reproduce the 
 * 		above copyright notice, this list of conditions 
 * 		and the following disclaimer in the documentation 
 * 		and/or other materials provided with the distribution.
 * 
 * 	THIS SOFTWARE IS PROVIDED "AS IS," WITHOUT A WARRANTY OF 
 * 	ANY KIND. ALL EXPRESS OR IMPLIED CONDITIONS, REPRESENTATIONS 
 * 	AND WARRANTIES, INCLUDING ANY IMPLIED WARRANTY OF MERCHANTABILITY, 
 * 	FITNESS FOR A PARTICULAR PURPOSE OR NON-INFRINGEMENT, 
 * 	ARE HEREBY EXCLUDED. OBIX LABS LIMITED ("Obix Labs") AND ITS 
 * 	LICENSORS SHALL NOT BE LIABLE FOR ANY DAMAGES SUFFERED BY LICENSEE 
 * 	AS A RESULT OF USING, MODIFYING OR DISTRIBUTING THIS SOFTWARE OR 
 * 	ITS DERIVATIVES. IN NO EVENT WILL Obix Labs OR ITS LICENSORS BE 
 * 	LIABLE FOR ANY LOST REVENUE, PROFIT OR DATA, OR FOR DIRECT, 
 * 	INDIRECT, SPECIAL, CONSEQUENTIAL, INCIDENTAL OR PUNITIVE 
 * 	DAMAGES, HOWEVER CAUSED AND REGARDLESS OF THE THEORY OF 
 * 	LIABILITY, ARISING OUT OF THE USE OF OR INABILITY TO USE THIS 
 * 	SOFTWARE, EVEN IF Obix Labs HAS BEEN ADVISED OF THE POSSIBILITY OF 
 * 	SUCH DAMAGES.
 */
package com.obixlabs.commons.security;

import java.util.List;

import com.obixlabs.commons.ObixException;

/**
 * <p>
 * Obix provided implementation of the {@link PasswordGenerator password generator interface}. This 
 * implementation simply initializes a {@link PasswordBuffer password buffer} and repeatedly applies the specified 
 * {@link PasswordRequirement password rules} to it.
 *</p>
 *
 *@see PasswordGenerator
 */
public class PasswordGeneratorDefaultImpl implements PasswordGenerator
{
	@Override
	public String generatePassword(List<PasswordRequirement> requirements) throws ObixException
	{ return generatePassword(requirements, -1); }

	@Override
	public String generatePassword(List<PasswordRequirement> requirements, int maximumLength) throws ObixException
	{
		PasswordBuffer result = new PasswordBuffer(maximumLength);
		for (PasswordRequirement passwordRequirement : requirements)
		{
			if (!passwordRequirement.apply(result))
				throw new ObixException("Failed to apply password requirement '" + passwordRequirement.getDescription() + 
																	"'. Ensure buffer has adequate size and that requirements do not conflict.");
		}
		return result.toString();
	}	
}